//
//  MainViewController.m
//  cityStar
//
//  Created by wangjia on 14/12/13.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "MainViewController.h"
#import "HTDefine.h"
#import "SideViewController.h"
#import "kata_IndexTitleViewController.h"
#import "CommonUtil.h"
#import "kata_StopViewController.h"
#import "SGFocusImageFrame.h"
#import "SGFocusImageItem.h"

#import "HWSearchViewController.h"
#import "INTULocationManager.h"
#import "CityPaysViewController.h"
#import "PoiSearchDemoViewController.h"

#import "RecruitmentViewController.h"
#import "LawViewController.h"
#import "HomeEconomicsListViewController.h"
#import "CarpoolingViewController.h"
#import "CityServiceViewController.h"
#import "OtherViewController.h"
#import "MakefriendsViewController.h"
#import "VideoViewController.h"
#import "BusLineSearchViewController.h"
#import "RouteSearchDemoViewController.h"

#import "WaresDetailViewController.h"
#import "RepairAndHomeViewController.h"

//购物车待删除
#import "DeliveryAddressViewController.h"
#import "AddDeliveryViewController.h"
#import "SelectDistributionViewController.h"
#import "HttpRequestManager.h"
#import "SelectCityViewController.h"
#import "selectCity.h"
#import "selectDistrict.h"
#import "merchantList.h"


@interface MainViewController ()<SGFocusImageFrameDelegate,localDelegate,CLLocationManagerDelegate,CLLocationManagerDelegate>
{
    kata_IndexTitleViewController *tvcTitle;
}
@property (strong,nonatomic) SGFocusImageFrame *bannerView;

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;
@property (nonatomic, strong) NSArray *bannerArray;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"城星微城市";
    //1233423425
    
    //初始化位置管理器
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
    
    UISwipeGestureRecognizer* recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:recognizer];
    
    UIButton * regBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    regBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [regBtn setTitleColor:rgba(133, 133, 133, 1) forState:UIControlStateHighlighted];
    [regBtn setImage:[UIImage imageNamed:@"bsearch_s"] forState:UIControlStateNormal];
    [regBtn setImage:[UIImage imageNamed:@"bsearch_s_touch"] forState:UIControlStateHighlighted];
    [regBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * iHaveNewsBtnItem = [[UIBarButtonItem alloc]initWithCustomView:regBtn];
    self.navigationItem.rightBarButtonItem = iHaveNewsBtnItem;
    
    UIButton *btnSide = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnSide setImage:[UIImage imageNamed:@"more_s"] forState:UIControlStateNormal];
    [btnSide setImage:[UIImage imageNamed:@"more_s_touch"] forState:UIControlStateHighlighted];
    [btnSide addTarget:self action:@selector(sideMove) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bbtmLeft = [[UIBarButtonItem alloc]initWithCustomView:btnSide];
    self.navigationItem.leftBarButtonItem = bbtmLeft;
    //    self.svContetn.aryTag = @[@"hahah",@"heheh",@"chacha"];
    //    self.svContetn.aryImage = @[@"banner",@"banner",@"banner"];
    
    tvcTitle = [[kata_IndexTitleViewController alloc]init];
    [self.svSelectLocal addSubview:tvcTitle.view];
    // Do any additional setup after loading the view.
    [self getAddressOfCityStar];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:8];
    NSTimeInterval nowTime=[dat timeIntervalSince1970];
    NSString *strNowTime = [NSString stringWithFormat:@"%f",nowTime];
    NSString *tokenTime = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsexpires];
    if ([strNowTime intValue] - [tokenTime intValue] > 0) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:KUserDefaultKey_PersonalDetail];
        [self getCitystarHttpToken];
    }else{
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsToken];
        DLog(@"%@",token);
        [[SVHTTPClient sharedClient] setValue:token forHTTPHeaderField:@"TOKEN"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(btnLockCityName:) name:@"showAlertView" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(btnLockCityNameArray:) name:@"showCityArray" object:nil];
        tvcTitle.delegate  = self;
    
}

#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [self webRequest_GetBannerMessgaeWithCityID:str];
        }else{
            
        }
    }];
}

//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorMsg = nil;
    if ([error code] == kCLErrorDenied) {
        errorMsg = @"访问被拒绝";
    }
    if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = @"获取位置信息失败";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
                                                       message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
    [alertView show];
}

-(void)webRequest_GetBannerMessgaeWithCityID:(NSString *)cityID
{
    NSString *personalCityID = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID];
    NSString *postUrl = @"";
    if (personalCityID) {
        postUrl = [NSString stringWithFormat:@"%@%@/%@",KinterFace_bannerShow,@"0",personalCityID];
    }else{
        postUrl = [NSString stringWithFormat:@"%@%@/%@",KinterFace_bannerShow,@"0",cityID];
    }
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        DLog(@"%@",response);
        if (success) {
            self.bannerArray = [[NSArray alloc]initWithArray:response[@"value"]];
            [self setbannerView];
//            [SVProgressHUD showSuccessWithStatus:@"win"];
        }else {
            if ([response[@"code"] intValue] == 403) {
                [self getCitystarHttpToken];
            }
//            [SVProgressHUD showErrorWithStatus:@"filed"];
        }
    }];
    
}

-(void)webRequest_citydataWithDetailID
{
        NSString *getPul = [NSString stringWithFormat:@"%@",KInterface_getProvince];
        [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                DLog(@"%@",response);
                [[selectCity shardUserInfo]setClasscityArray:response[@"value"]];
            }else{
                DLog(@"%@",errMsg);
                [SVProgressHUD showErrorWithStatus:errMsg];
          }
       }];
}


-(void)viewWillAppear:(BOOL)animated
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0) {
        self.navigationController.navigationBar.translucent = NO; //禁止半透明毛玻璃效果
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; //返回按钮颜色
        self.navigationController.navigationBar.barTintColor = rgba(255, 155, 95, 1); //bar背景颜色
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    }else{
        self.navigationController.navigationBar.barTintColor = rgba(255, 155, 95, 1); //bar背景颜色
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    }
    [self webRequest_GetBannerMessgaeWithCityID:@"122"];
}

- (void)btnLockCityNameArray:(NSNotification *)notification
{
    NSMutableArray *cityArray = (NSMutableArray *)notification.object;
    
    NSMutableArray *newCityArray = [[NSMutableArray alloc]init];
    for (NSString *stringName in cityArray[0])
    {
        NSString * newname = [stringName stringByReplacingOccurrencesOfString:@"市" withString:@""];
        [newCityArray addObject:newname];
    }
    NSMutableArray *idCityArray = [[NSMutableArray alloc]initWithArray:cityArray[1]];
    [tvcTitle setAryFiveTitle:newCityArray andCityID:idCityArray];
}


- (void)btnLockCityName:(NSNotification *)notification
{
    NSMutableString *stringName = (NSMutableString *)notification.object;
    NSString * newname = [stringName stringByReplacingOccurrencesOfString:@"市" withString:@""];
//    NSRange range = [stringName rangeOfString:@"市"];
//    NSInteger location = range.location ;
//    [stringName deleteCharactersInRange:NSMakeRange(location, 1)];
    [self changeLocalByCityName:newname];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - chnageCityTitileDelegate
-(void)didSelectCitySender
{
    SelectCityViewController *selectCityViewController = [[SelectCityViewController alloc]init];
    [self.navigationController pushViewController:selectCityViewController animated:YES];
}

#pragma mark - webRequest
-(void)getCitystarHttpToken
{
    [HttpRequestManager getMethod:KInterface_getToken parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            [[NSUserDefaults standardUserDefaults] setObject:response[@"value"][@"token"] forKey:KUserDefaultsToken];
            [[NSUserDefaults standardUserDefaults] setObject:response[@"value"][@"expires"] forKey:KUserDefaultsexpires];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[SVHTTPClient sharedClient] setValue:response[@"value"][@"token"] forHTTPHeaderField:@"TOKEN"];
//            [self webRequest_citydataWithDetailID];
        }
        DLog(@"%@",response);
    }];
}

-(void)setbannerView
{
    DLog(@"%@",self.bannerArray);
    if(self.bannerArray.count > 0)
    {
    NSMutableArray *tempArray = [NSMutableArray array];
    __block NSInteger length;
    if (self.bannerArray) {
        [self.bannerArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
            NSString *strimagepath = [NSString stringWithFormat:@"http://api.icszx.com/image/c/id/%@/w/640/h/300/m/1",self.bannerArray[idx][@"image"]];
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:strimagepath,@"imagePath",nil];
            length = tempArray.count+1;
            [tempArray addObject:dict];
        }];

        
    }else{
        tempArray = [NSMutableArray array];
        length = 1;
        for (int i = 0 ; i < length; i++)
        {
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"banner",@"imagePath",nil];
            [tempArray addObject:dict];
        }
    }
    //添加最后一张图 用于循环
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:length+2];
    if (length > 1)
    {
        NSDictionary *dict = [tempArray objectAtIndex:length-1];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:-1] ;
        [itemArray addObject:item];
    }
    for (int i = 0; i < length; i++)
    {
        NSDictionary *dict = [tempArray objectAtIndex:i];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:i];
        [itemArray addObject:item];
    }
    //添加第一张图 用于循环
    if (length >1)
    {
        NSDictionary *dict = [tempArray objectAtIndex:0];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:length];
        [itemArray addObject:item];
    }
    self.bannerView = [[SGFocusImageFrame alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) delegate:self imageItems:itemArray isAuto:NO];
    [self.bannerView scrollToIndex:2];
    [self.svContetn addSubview:self.bannerView];
    }else{
        UIImageView *imageBack = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
        imageBack.image = [UIImage imageNamed:@"品牌详情_主图"];
        [self.svContetn addSubview:imageBack];
    }
    
}


-(void)foucusImageFrame:(SGFocusImageFrame *)imageFrame didSelectItem:(SGFocusImageItem *)item ImagePage:(int)pageIndex
{
    if ([self.bannerArray[pageIndex-1][@"type"] intValue] == 2) {
        WaresDetailViewController *wareDetailVC = [[WaresDetailViewController alloc]initWithCommodityID:self.bannerArray[pageIndex-1][@"object_id"]];
        [self.navigationController pushViewController:wareDetailVC animated:YES];
    }else if ([self.bannerArray[pageIndex-1][@"type"] intValue] == 1){
        RepairAndHomeViewController *repairAndHomeVC = [[RepairAndHomeViewController alloc]initWithMerchantID:self.bannerArray[pageIndex-1][@"object_id"]];
        [self.navigationController pushViewController:repairAndHomeVC animated:YES];
    }
    
}

#pragma mark - Action

-(void)getAddressOfCityStar
{
        __weak __typeof(self) weakSelf = self;
        static BOOL firstFailed = YES;
        INTULocationManager *locMgr = [INTULocationManager sharedInstance];
        [locMgr requestLocationWithDesiredAccuracy:INTULocationAccuracyCity timeout:1 delayUntilAuthorized:YES block:^(CLLocation *currentLocation, INTULocationAccuracy INTULocationAccuracyBlock, INTULocationStatus status) {
            
            //TODO:网络请求,有几家机构
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if (status == INTULocationStatusSuccess||status == INTULocationStatusTimedOut||currentLocation) {
                
                CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
                CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error)
                {
                    for (CLPlacemark * placeMark in placemarks)
                    {
                        //比如：滨江区
                        NSDictionary *addressDic = placeMark.addressDictionary;
                        DLog(@"%@",addressDic);
                        NSString *subLocality = addressDic[@"SubLocality"];
                        NSString *city = addressDic[@"City"];
                        NSString * newname = [city stringByReplacingOccurrencesOfString:@"市" withString:  @""];
                        [self changeLocalByCityName:newname];
                        return ;
                    }
                };
                [clGeoCoder reverseGeocodeLocation:currentLocation completionHandler:handle];
                
            }else{
                if (status == INTULocationStatusError) {
//                    strongSelf.currentlocation_Lbl.text = @"定位失败";
                }else{
                    //定位失败，可能未获得权限
                    if (firstFailed) {
//                        FastAlertViewWithTitle(@"请允许求学记获得定位权限，才可能获取周边机构...");
                        firstFailed = NO;
                    }
//                    strongSelf.currentlocation_Lbl.text = @"请开启定位";
                }
//                strongSelf.hasGetLocation = NO;
            }
        }];
}

-(void)changeLockBtnName
{
    [self webRequest_GetBannerMessgaeWithCityID:@"122"];
}

-(void)changeLocalByCityName:(NSString *)cityName
{
    NSString *strName = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityName];
    if (strName) {
        [tvcTitle.btnLock setTitle:strName forState:UIControlStateNormal];
    }else{
        [tvcTitle.btnLock setTitle:cityName forState:UIControlStateNormal];
    }
}

- (void)searchAction{
    HWSearchViewController *hwSearchVC = [[HWSearchViewController alloc]init];
    hwSearchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hwSearchVC animated:YES];
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    [self sideMove];
//    [self.view removeGestureRecognizer:recognizer];
}

- (void)sideMove{
    [[SideViewController shareVc] showLeftView];
}

- (IBAction)typeAction:(UIButton *)sender {
    NSLog(@"%ld",(long)sender.tag);
    
    //城市动态
    if (sender.tag == 1) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alert show];
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SICityDynamic"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    //城市社区
    if (sender.tag == 2) {
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SICityCommunity"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    //城市微博
    if(sender.tag == 3){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alert show];
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SIWeiBo"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    //玩转城市
    if(sender.tag == 4){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alert show];
//        merchantList *CommodityViewController2 = [[merchantList alloc] init];
//        [self.navigationController pushViewController:CommodityViewController2 animated:true];
        
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SIPlayGround"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
    //品牌商城
    if (sender.tag == 5) {
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SIBrand"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
    //城市活动
    if (sender.tag == 6) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alert show];
        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SICityActivityTotal"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
    //城市服务
    if(sender.tag == 7){
        CityServiceViewController *CommodityViewController = [[CityServiceViewController alloc] init];
        [self.navigationController pushViewController:CommodityViewController animated:true];
    }
    
    //城市活动
    if (sender.tag == 8) {

        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SICityStreet"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
    //银联支付
    if (sender.tag == 9) {
//        CityPaysViewController *cityPayViewController = [[CityPaysViewController alloc] init];
//        [self.navigationController pushViewController:cityPayViewController animated:true];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
//        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"Index" identify:@"SIPay"];
//        [self.navigationController pushViewController:viewController animated:YES];
    }
    
    //停车
    if (sender.tag == 10) {
        kata_StopViewController *stopVC = (kata_StopViewController *)[CommonUtil getVCWithSbIden:@"IndexFour" identify:@"VCStop"];
        stopVC.intID = 4218;
        [self.navigationController pushViewController:stopVC animated:YES];
    }
    
    //代驾
    if (sender.tag == 11) {
        kata_StopViewController *stopVC = (kata_StopViewController *)[CommonUtil getVCWithSbIden:@"IndexFour" identify:@"VCStop"];
        stopVC.intID = 4217;
        [self.navigationController pushViewController:stopVC animated:YES];
    }
    
    //公交
    if (sender.tag == 12) {
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alert show];
        PoiSearchDemoViewController *routeSearchVC = [[PoiSearchDemoViewController alloc]init];
        [self.navigationController pushViewController:routeSearchVC animated:YES];
//        UIViewController *viewController = [CommonUtil getVCWithSbIden:@"IndexFour" identify:@"SIBus"];
//        [self.navigationController pushViewController:viewController animated:YES];
    }
    //满赚
    if (sender.tag == 13) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"正在建设中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
    
    
}
@end
